package cn.iocoder.yudao.module.call.service.ivrflowvoice;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.call.util.TmtUtil;
import cn.iocoder.yudao.module.system.api.extend.ExtendApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import cn.iocoder.yudao.module.call.controller.admin.ivrflowvoice.vo.*;
import cn.iocoder.yudao.module.call.dal.dataobject.ivrflowvoice.IvrFlowVoiceDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.call.dal.mysql.ivrflowvoice.IvrFlowVoiceMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.call.enums.ErrorCodeConstants.*;

/**
 * ivr流程-语音文件 Service 实现类
 *
 * @author 数创万维
 */
@Service
@Validated
public class IvrFlowVoiceServiceImpl implements IvrFlowVoiceService {

    @Resource
    private IvrFlowVoiceMapper ivrFlowVoiceMapper;

    @Resource
    private ExtendApi extendApi;

    @Override
    public Long createIvrFlowVoice(IvrFlowVoiceSaveReqVO createReqVO) {
        // 插入
        IvrFlowVoiceDO ivrFlowVoice = BeanUtils.toBean(createReqVO, IvrFlowVoiceDO.class);
        InputStream inputStream = null;
        try {
            inputStream = getFileFromUrl(ivrFlowVoice.getFilePath());
            // 将文件转换为字节数组
            byte[] fileBytes = convertStreamToBytes(inputStream);
            String base64String = encodeToBase64(fileBytes);
            Map<String, Object> params = new HashMap<String, Object>() {{
                put("byte", base64String);
                put("type", "file");
            }};
            extendApi.setDomain("http://scrmextend.com:8081");
            JSONObject agentState = extendApi.request("/index/ivrUpload", JSONUtil.toJsonStr(params));
            String filePath = agentState.getStr("filePath");
            String localPath = agentState.getStr("localPath");

            String content = TmtUtil.tengXunTmt(base64String);
            ivrFlowVoice.setFileContent(content);
            ivrFlowVoice.setFilePath(filePath);
            ivrFlowVoice.setLocalPath(localPath);
            ivrFlowVoiceMapper.insert(ivrFlowVoice);
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
        // 返回
        return ivrFlowVoice.getId();
    }
    private static String encodeToBase64(byte[] data) {
        return Base64.getEncoder().encodeToString(data);
    }
    // 从 URL 获取文件输入流
    private static InputStream getFileFromUrl(String fileUrl) throws Exception {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000); // 设置连接超时时间
        connection.setReadTimeout(5000);    // 设置读取超时时间
        return connection.getInputStream();
    }
    // 将输入流转换为字节数组
    private static byte[] convertStreamToBytes(InputStream inputStream) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }
        return byteArrayOutputStream.toByteArray();
    }

    @Override
    public void updateIvrFlowVoice(IvrFlowVoiceSaveReqVO updateReqVO) {
        // 校验存在
        validateIvrFlowVoiceExists(updateReqVO.getId());
        // 更新
        IvrFlowVoiceDO updateObj = BeanUtils.toBean(updateReqVO, IvrFlowVoiceDO.class);
        ivrFlowVoiceMapper.updateById(updateObj);
    }

    @Override
    public void deleteIvrFlowVoice(Long id) {
        // 校验存在
        validateIvrFlowVoiceExists(id);
        // 删除
        ivrFlowVoiceMapper.deleteById(id);
    }

    private void validateIvrFlowVoiceExists(Long id) {
        if (ivrFlowVoiceMapper.selectById(id) == null) {
            throw exception(IVR_FLOW_VOICE_NOT_EXISTS);
        }
    }

    @Override
    public IvrFlowVoiceDO getIvrFlowVoice(Long id) {
        return ivrFlowVoiceMapper.selectById(id);
    }

    @Override
    public PageResult<IvrFlowVoiceDO> getIvrFlowVoicePage(IvrFlowVoicePageReqVO pageReqVO) {
        return ivrFlowVoiceMapper.selectPage(pageReqVO);
    }

    public List<IvrFlowVoiceDO> getIvrFlowVoiceByType(IvrFlowVoicePageReqVO pageReqVO) {
        LambdaQueryWrapper<IvrFlowVoiceDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IvrFlowVoiceDO::getType, pageReqVO.getType());
        return ivrFlowVoiceMapper.selectList(queryWrapper);
    }

}